import React from 'react';
import { connect } from 'dva';
import { Table, Row, Col, Form, Input, Radio, DatePicker, Select, Button, Modal, Popconfirm, message } from 'antd';
const R = require('ramda');
const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
import RightContacts from "../../../utils/RightConstants";
import EditCustomer from '../../../components/customer/components/EditCustomer';
import BizParams from '../../../components/commons/BizParams'
import CustomerDetail from '../../../components/customer/components/CustomerDetail';
import RightBox from "../../../components/commons/RightBox";
import Constants from "../../../utils/Constants";


const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
export default connect(({ customerManage, businessAgreement, lessee }) => ({ customerManage, businessAgreement, lessee }))(
    Form.create()(class customerManage extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                open: false,
            }
        }

        componentDidMount() {
            this.props.dispatch({
                type: 'customerManage/queryCustomerManageList',
                payload: {
                    status: 1,
                    businessType: Constants.NUMBER_ONE
                }
            });
        }

        handleAdd = () => {
            this.setState({ open: true });
        }

        collectSearchCondition = () => {
            let conditions = this.props.form.getFieldsValue();
            conditions.page = this.props.customerManage.page;
            return conditions;
        }

        handleResetFields = () => {
            if (this.editCustomer) this.editCustomer.handleResetFields();
        }

        handleCancel = (flag) => {
            if (flag) {
                this.handleResetFields();
            }
            this.setState({ open: false });
        }

        onView = (record) => {
            this.handleOpenDetail(record, true, {}, "1", true);
        }

        onEdit = (record) => {
            this.handleOpenDetail(record, false, {}, "1", false);
        }

        handleOpenDetail = (record, customerDisabled, searchConditions, tabActiveKey, editCustomerDisable) => {
            this.props.dispatch({ type: 'customerManage/getCustomerById', payload: { id: record.id, isApproval: true } });
            this.props.dispatch({ type: 'customerManage/getLinkmanList', payload: { cstId: record.id, page: this.props.customerManage.linkmanPage } });//查询联系人列表
            this.props.dispatch({ type: 'customerManage/getAgencyagreementList', payload: { id: record.id, page: this.props.customerManage.agencyagreementPage } });
            this.props.dispatch({ type: 'businessAgreement/getAgreementlList', payload: { cstId: record.id, status: 1 } });
            this.props.dispatch({ type: 'customerManage/getListByCstIdForPage', payload: { cstId: record.id, page: this.props.customerManage.marketInfoPage } });

            this.refs.customerDetail.handleOpen(customerDisabled, searchConditions, tabActiveKey, record.id, editCustomerDisable, "customerManage",record.status,);
        }

        handleSearch = () => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.customerManage.page;
            newPage.page = 1;
            let time = values.time;


            this.props.dispatch({
                type: 'customerManage/queryCustomerManageList',
                payload: {
                    customerNO: values.customerNO,
                    cstName: values.cstName,
                    cstType: values.cstType,
                    cstManage: values.cstManage,
                    cstWaiter: values.cstWaiter,
                    status: values.status,
                    businessType: Constants.NUMBER_ONE,
                    page: newPage,
                    beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                    endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                }
            });
        };

        handleConfirm = () => {
            if (this.editCustomer) {
                if (this.editCustomer.checkCustomerInfo(this.props.dispatch, this.onSuccess) == true) {
                    this.handleSearch();
                }
            }
        };

        onSuccess = () => {
            this.handleSearch();
            this.handleCancel();
            this.handleResetFields();
        };


        columns = [
            { title: '客户编码', dataIndex: 'customerno', key: 'customerno' },

            { title: '客户名称', dataIndex: 'companyname', key: 'companyname', },

            {
                title: '客户类型', render(record) {
                    if (R.isNil(record.companytypeName) || R.isEmpty(record.companytypeName)) {
                        return "未分配"
                    } else {
                        return record.companytypeName;
                    }
                }
            },

            {
                title: '业务经理', render(record) {
                    if (R.isNil(record.managerName) || R.isEmpty(record.managerName)) {
                        return "未分配";
                    } else {
                        return record.managerName;
                    }
                }
            },

            {
                title: '跟单经理', render(record) {
                    if (R.isNil(record.waiterName) || R.isEmpty(record.waiterName)) {
                        return "未分配";
                    } else {
                        return record.waiterName;
                    }
                }
            },

            { title: '创建时间', dataIndex: 'createtime', key: 'createtime' },

            {
                title: '操作', key: 'key_oprator',

                render: (text, record, index) => {
                    let deleteButton =
                        <RightBox resource={RightContacts.CUSTOMER.CUSTOMER_MANAGE_CUSTOMER_DELETE} >
                            <Popconfirm placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除？'} onConfirm={() => {
                                if (record.csttype === '1') {
                                    message.info("当前是会员客户，不允许删除！");
                                    return;
                                }
                                this.props.dispatch({
                                    type: 'customerManage/deleteCustomerById',
                                    payload: {
                                        id: record.id,
                                        onSuccess: () => {
                                            this.handleSearch();
                                        }
                                    }
                                });
                            }} okText="是" cancelText="否">
                                <a href="#">删除</a>

                            </Popconfirm></RightBox>;


                    let editButton = <RightBox resource={RightContacts.CUSTOMER.CUSTOMER_MANAGE_CUSTOMER_EDIT} split={false}>
                        {record.status === "1" || record.status === "3" ?
                            <span><a href="#" onClick={this.onEdit.bind(this, record)}>编辑</a> <span className="ant-divider" /></span> : ''}

                    </RightBox>;



                    deleteButton = record.status === "1" || record.status === "3" ? deleteButton : "";
                    let split = deleteButton === "" ? "" : <span className="ant-divider" />;
                    return (
                        <span>
                            {record.status === "1" || record.status === "3" ? editButton : ''}
                            {deleteButton}

                            {record.status === "2" || record.status === "4" || record.status === "5" ?
                                <a href="#" onClick={this.onView.bind(this, record)}>查看</a> : ''}
                        </span>
                    );
                }
            }
        ];

        render() {
            let dataSouce = R.isNil(this.props.customerManage.dataSource) ? {} : this.props.customerManage.dataSource;
            let formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
            const { getFieldDecorator } = this.props.form;
            let values = this.props.form.getFieldsValue();
            let time = values.time;
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                pageSize: this.props.customerManage.page.size,
                total: this.props.customerManage.page.totalRow,
                showSizeChanger: true,
                current: this.props.customerManage.page.page,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.customerManage.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'customerManage/queryCustomerManageList',
                        payload: {
                            customerNO: values.customerNO,
                            cstName: values.cstName,
                            cstType: values.cstType,
                            cstManage: values.cstManage,
                            cstWaiter: values.cstWaiter,
                            status: values.status,
                            businessType: Constants.NUMBER_ONE,
                            page: newPage,
                            beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                            endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = this.props.customerManage.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'customerManage/queryCustomerManageList',
                        payload: {
                            customerNO: values.customerNO,
                            cstName: values.cstName,
                            cstType: values.cstType,
                            cstManage: values.cstManage,
                            cstWaiter: values.cstWaiter,
                            status: values.status,
                            businessType: Constants.NUMBER_ONE,
                            page: newPage,
                            beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                            endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                        }
                    });
                }
            }
            return (
                <div>

                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户代码'}>{getFieldDecorator('customerNO')(<Input />)}</FormItem></Col>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('cstName')(<Input />)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'业务经理'}>{getFieldDecorator('cstManage')(<Input />)}</FormItem></Col>
                        <Col span={7}><FormItem {...formItemLayout} label={'跟单经理'}>{getFieldDecorator('cstWaiter')(<Input />)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户类型'}>
                            {getFieldDecorator('cstType')(
                                <BizParams sprCode={"cstType"} style={{ width: '100%' }} all={true} />
                            )}
                        </FormItem></Col>
                        <Col span={7}>
                            <FormItem {...formItemLayout} label={'创建时间'}>
                                {getFieldDecorator('time', {})(
                                    <RangePicker
                                        style={{ width: 265 }}
                                        showTime={{ format: 'YYYY-MM-DD' }}
                                        format="YYYY-MM-DD"
                                        placeholder={['开始时间', '结束时间']}
                                    />
                                )}
                            </FormItem>
                        </Col>

                    </Row>
                    <Row>
                        <Col span={7}>
                            <FormItem {...formItemLayout} label={'状态'}>
                                {getFieldDecorator('status', {
                                    initialValue: "1"
                                })(

                                    <RadioGroup style={{ width: 800 }}>
                                        <Radio value="1">待申请</Radio>
                                        <Radio value="2">待审核</Radio>
                                        <Radio value="3">待补充资料</Radio>
                                        <Radio value="4">审核通过</Radio>
                                        <Radio value="5">审核不通过</Radio>
                                    </RadioGroup>
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={7} style={{ float: 'right' }}>
                            <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this)}>查询</Button>
                            <RightBox resource={RightContacts.CUSTOMER.CUSTOMER_MANAGE_CUSTOMER_ADD}><Button type="primary" icon="plus" style={{ marginRight: 5 }} onClick={this.handleAdd.bind(this)}>创建客户</Button></RightBox>

                        </Col>
                    </Row>

                    <Table dataSource={this.props.customerManage.list} columns={this.columns} bordered={true}
                        size={'middle'} pagination={pagination} />

                    <CustomerDetail ref={"customerDetail"} cstId={dataSouce.cstid} {...this.props.customerManage}
                        businessAgreement={this.props.businessAgreement} dispatch={this.props.dispatch}
                        handleSearch={this.handleSearch} />

                    <Modal maskClosable={false} visible={this.state.open} title={"编辑客户"} width={1200}
                        wrapClassName="vertical-center-modal" onCancel={this.handleCancel} onOk={this.handleConfirm}>
                        <EditCustomer wrappedComponentRef={(inst) => this.editCustomer = inst} type={"add"}
                             handleSearch={this.handleSearch} />
                    </Modal>
                </div>
            )
        }
    })


)
